//
//  LoginViewController.swift
//  Nairacup
//
//  Created by ec on 2024/9/19.
//

import UIKit

class LoginViewController: UIViewController {

    @IBOutlet weak var phoneView: UIView!
    @IBOutlet weak var codeView: UIView!
    @IBOutlet weak var phoneTF: UITextField!
    @IBOutlet weak var codeTF: UITextField!
    @IBOutlet weak var sendBtn: UIButton!
    @IBOutlet weak var optLabel: UILabel!
    @IBOutlet weak var stateBtn: UIButton!
    @IBOutlet weak var loginBtn: UIButton!
    
    // 注册输入页 停留时长 ms
    var trackRegGuideTime: Int = 0
    // 注册输入页- phone-input 获焦失焦 时间差 ms
    var trackRegGuidePhoneTime: Int = 0
    // 注册输入页- phone-input 修改次数
    var trackRegGuidePhoneUpNum: Int = 0
    // 注册输入页- phone-input 输入次数
    var trackRegGuidePhoneInNum: Int = 0
    // 注册输入页- code-input  获焦失焦 时间差 ms
    var trackRegGuideCodeTime: Int = 0
    // 注册输入页- code-input 修改次数
    var trackRegGuideCodeUpNum: Int = 0
    // 注册输入页- code-input 输入次数
    var trackRegGuideCodeInNum: Int = 0
    // 注册输入页- 发送验证码按钮点击次数
    var trackRegGuideCodeButNum: Int = 0
    // 注册输入页- 注册登录按钮点击次数
    var trackRegGuideRegButNum: Int = 0
    // 引导页面停留时间 ms
    var trackGuidePageTime: Int = 0
    // 引导页申请按钮点击次数
    var trackGuidePageButNum: Int = 0
    var privacypolicyUrl = ""      // protocalType=1
    var customerAgreementUrl = ""  // protocalType=6
    var code: String = "234"
    var cutTime = -1

    override func viewDidLoad() {
        super.viewDidLoad()
        navigationController?.setNavigationBarHidden(true, animated: false)

        let tap = UITapGestureRecognizer(target: self, action: #selector(actionTap))
        view.addGestureRecognizer(tap)
        
        NotificationCenter.default.addObserver(self, selector: #selector(valueChanged), name: UITextField.textDidChangeNotification, object: nil)
        
        let auth = AuthViewController(nibName: "AuthViewController", bundle: nil)
        auth.modalPresentationStyle = .fullScreen
        present(auth, animated: false)

        requestProtocol()
    }

    func requestProtocol() {
        Request.shared.requestApi(.getProtocol) { [weak self] response in
            if (response["code"] as? Int) == 200, let list = response["data"] as? [[String: Any]] {
                guard let self = self else { return }
                self.privacypolicyUrl = list.filter({ $0["protocalType"] as? Int == 1 }).first?["url"] as? String ?? ""
                self.customerAgreementUrl = list.filter({ $0["protocalType"] as? Int == 6 }).first?["url"] as? String ?? ""
            }
        }
    }
    
    override func viewDidLayoutSubviews() {
        phoneView.addShadow()
        codeView.addShadow()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    func startCutTime() {
        cutTime -= 1
        if cutTime < 0 {
            sendBtn.isSelected = true
            optLabel.text = "OPT"
        }else {
            sendBtn.isSelected = false
            optLabel.text = "\(cutTime)s"

            Async.main(after: 1) { [weak self] in
                self?.startCutTime()
            }
        }
    }

    @objc func actionTap() {
        view.endEditing(true)
    }
    
    @objc func valueChanged() {
        let text = phoneTF.text ?? ""
        if phoneTF.isEditing, text.count>3 {
            var nums = text.map { String($0) }
            if nums[3] != "-" {
                nums.insert("-", at: 3)
            }
            if nums.count>8, nums[8] != "-" {
                nums.insert("-", at: 8)
            }
            phoneTF.text = nums.joined()
            Async.main(after: 0.1) { [weak self] in
                // 光标移动到最后
                let position = self?.phoneTF.endOfDocument
                self?.phoneTF.selectedTextRange = self?.phoneTF.textRange(from: position!, to: position!)
            }
        }

        var regx = (phoneTF.text ?? "").replacingOccurrences(of: "-", with: "").count != 10
        if !regx {
            if NSString(string: phoneTF.text!).substring(to: 1) == "0" {
                regx = true
            }
        }
        if phoneTF.isEditing && cutTime < 0 {
            sendBtn.isSelected = !regx
        }
        
        if (codeTF.text ?? "").count > 4 {
            codeTF.text = NSString(string: codeTF.text!).substring(to: 4)
        }

        loginBtn.setBackgroundImage(UIImage(named:regx || (codeTF.text ?? "").count != 4 ? "login_btn_n" : "login_btn_s"), for: .normal)
    }

    @IBAction func actionProtocol1(_ sender: Any) {
        if privacypolicyUrl.isEmpty {
            return
        }
        let vc = WebViewController()
        vc.url = URL(string: privacypolicyUrl)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func actionProtocol2(_ sender: Any) {
        if customerAgreementUrl.isEmpty {
            return
        }
        let vc = WebViewController()
        vc.url = URL(string: customerAgreementUrl)
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @IBAction func actionSendCode(_ sender: Any) {
        phoneTF.resignFirstResponder()
        if (phoneTF.text ?? "").replacingOccurrences(of: "-", with: "").count != 10 {
            showToast("Please fill in correct phone number")
            return
        }
        if cutTime < 0 {
            cutTime = 60
            requestCode()
        }
    }
    
    @IBAction func actionStatus(_ sender: Any) {
        stateBtn.isSelected = !stateBtn.isSelected
    }
    
    @IBAction func actionLogin(_ sender: Any) {
        phoneTF.resignFirstResponder()
        codeTF.resignFirstResponder()
        if (phoneTF.text ?? "").replacingOccurrences(of: "-", with: "").count != 10 {
            showToast("Please fill in correct phone number")
            return
        }
        if (codeTF.text ?? "").isEmpty || (codeTF.text ?? "").count != 4 {
            showToast("Please check your OTP")
            return
        }
        if !stateBtn.isSelected {
            showToast("Please agree the agreements")
            return
        }
    }
    
    func requestCode() {
        Request.shared.requestApi(.sendCode(phone: phoneTF.text ?? "")) { [weak self] response in
            if (response["code"] as? Int) == 200 {
                self?.startCutTime()
            }
        }
    }
    
    func requestLogin() {
        var version = "1.0.0"
        if let infoDictionary = Bundle.main.infoDictionary {
            if let versionString = infoDictionary["CFBundleShortVersionString"] as? String {
                version = versionString
            }
        }
        Request.shared.requestApi(.login(device: DeviceModel(phone: phoneTF.text!, code: codeTF.text!, mobilePhoneBrands: "Apple", appMarketCode: "AppleStore", appsFlyerId: "", deviceModel: UIDevice.current.phoneModel, channelCode: "", version: version, client: "ios", extensionS: "", adjustId: ""))) { [weak self] response in
            if (response["code"] as? Int) == 200, let self = self {
                if let data = response["data"] as? [String: Any], let userId = data["userId"] as? String, let sessionId = data["sessionId"] as? String {
                    UserDefaults.standard.setValue(sessionId, forKey: Adapt.loginSessionId)
                    UserDefaults.standard.setValue(userId, forKey: Adapt.loginUserId)
                    UserDefaults.standard.setValue(self.phoneTF.text, forKey: Adapt.loginUserPhone)
                    if let jsonData = try? JSONSerialization.data(withJSONObject: data, options: .prettyPrinted), let jsonString = String(data: jsonData, encoding: .utf8) {
                        UserDefaults.standard.setValue(jsonString, forKey: Adapt.loginUserInfo)
                    }
                    self.requestUploadIosAction()
                    NotificationCenter.default.post(name: NSNotification.Name(Adapt.loginStatusChanged), object: nil)
                }
            }
        }
    }
    
    func requestUploadIosAction() {
        Request.shared.requestApi(.uploadIosAction([
            "type": 1,
            "trackRegGuideTime": trackRegGuideTime,
            "trackRegGuidePhoneTime": trackRegGuidePhoneTime,
            "trackRegGuidePhoneUpNum": trackRegGuidePhoneUpNum,
            "trackRegGuidePhoneInNum": trackRegGuidePhoneInNum,
            "trackRegGuideCodeTime": trackRegGuideCodeTime,
            "trackRegGuideCodeUpNum": trackRegGuideCodeUpNum,
            "trackRegGuideCodeInNum": trackRegGuideCodeInNum,
            "trackRegGuideCodeButNum": trackRegGuideCodeButNum,
            "trackRegGuideRegButNum": trackRegGuideRegButNum,
            "trackGuidePageTime": trackGuidePageTime,
            "trackGuidePageButNum": trackGuidePageButNum,
        ])) { response in
            
        }
    }

}

extension LoginViewController: UITextFieldDelegate {
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        return textField.resignFirstResponder()
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == phoneTF {
            if (textField.text ?? "").replacingOccurrences(of: "-", with: "").count + string.count > 10 {
                return false
            }
        }
        return true
    }
}
